<template>
  <div>
    <Form ref='productNormstemplateObj' :model="productNormstemplateObj" :rules="ruleValidate" :label-width="100">
      <FormItem label="模板名称" prop="name">
        <Input v-model="productNormstemplateObj.name" placeholder="请输入模板名称"></Input>
      </FormItem>
      <FormItem label="顶级规格分类">
        <Button @click='classList' type="primary" icon="md-settings">立即设置</Button>
      </FormItem>
      <FormItem label="" v-if='productNormstemplateObj.template_norms_property_name'>
        <Button class='p-relative-top' type="success" size='small'>{{productNormstemplateObj.template_norms_property_name}}</Button>
      </FormItem>
      <FormItem label="规格选择">
        <Button @click='selectType' type="primary" icon="md-settings">立即设置</Button>
      </FormItem>
      <FormItem label="">
        <Button v-show="item.property_value_name" class='p-relative-top' type="success" size='small' v-for="(item,index) in productNormstemplateObj.norms">
          {{item.property_value_name}}
        </Button>

      </FormItem>
    </Form>
    <!-- 弹窗 -->
    <Modal v-model="prodModal" title="选择关联产品" width='65%'>
      <div class="p-relative">
        <div class="flex-box search-area">
          <div class="flex-item">
            <Input v-model="searchObj.name" placeholder="请输入规格模板名称"></Input>
          </div>
          <div class="flex-item search-btn" @click="search">
            <Button type="primary">搜索</Button>
          </div>
          <div class="flex-item search-btn" @click="reset">
            <Button>重置</Button>
          </div>
        </div>
      </div>
      <Table :columns="tableOption" :data="data.list" border :no-data-text="loadingText ? loadingText : '暂无数据'" border
        ref="tables" editable search-place="top">
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">

            <!-- <Button type='primary' @click="edit(row, index)" size='small'>修改</Button> -->
            <Button type='primary' @click="select(row, index)" size='small'>选择</Button>
          </div>
        </template>
      </Table>

      <Page class="foot-page" :current='page.current' :total="page.total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changepage"></Page>
    </Modal>

    <!-- 设置规格 -->
    <Modal v-model="typeModal" title="设置规格9" width='65%'>
      <Form ref="normsValidate" :model="normsForm" :rules="normsRuleValidate" :label-width="80">
        <div class="g-row border-bottom-dash pad-bottom10 margin-bottom20">
          <div class="g-title pad-bottom20"></div>
          <div class="g-item">
            <div v-for="(item,index) in normsName">
              <FormItem :label="item.name">
                <CheckboxGroup v-model="item.itemGroup">
                  <Checkbox :label="row.id" v-for="(row,index) in item.sub">{{row.name}}</Checkbox>
                  <Input @on-blur="changeNewSub(index)" style="width: 100px;" v-for="(data,j) in item.new_sub" v-model='data.name'></Input>
                  <Button @click="addNormsItem(index)" size="small" type="primary">+</Button>
                </CheckboxGroup>

              </FormItem>

            </div>
          </div>
        </div>

        <FormItem label="自定义规格"></FormItem>
        <FormItem label="规格名称" prop="pidName" class=''>
          <Input v-for="(item,index) in secondForm" v-model="item.normsName" placeholder="规格名" style='width:100px;'></Input>
          <Button type="primary" @click='addClass'>添加</Button>
        </FormItem>
        <FormItem label="规格项" prop="pidName" class='' style="margin-bottom: 0;"></FormItem>
         <FormItem v-for="(item,index) in secondForm" v-if="item.normsName" :label="item.normsName">
           <!-- <span style="display: inline-block;width:80px;text-align: right;">{{item.normsName}}：</span> -->
           <Input v-for="(row,k) in item.sub" v-model="row.name" placeholder="规格项" style='width:100px;'></Input>
           <Button type="primary" @click='addItem(index)'>添加</Button>
         </FormItem>
       <!-- <FormItem prop="pidName" class=''>
          <div v-for="(item,index) in secondForm" v-if="item.normsName" style="margin-bottom: 10px;">
            <span style="display: inline-block;width:80px;text-align: right;">{{item.normsName}}：</span>
            <Input v-for="(row,k) in item.sub" v-model="row.name" placeholder="规格项" style='width:100px;'></Input>
            <Button type="primary" @click='addItem(index)'>添加</Button>
          </div>
        </FormItem> -->
      </Form>


      <!-- <div class="g-row border-bottom-dash pad-bottom20">
        <div class="g-title pad-bottom20 pad-top20">套餐</div>
        <CheckboxGroup v-model="type">
          <Checkbox label="7天"></Checkbox>
          <Checkbox label="15天"></Checkbox>
          <Checkbox label="30天"></Checkbox>
        </CheckboxGroup>
      </div>
      <div class="g-row pad-bottom10">
        <div class="g-title pad-bottom20 pad-top20">型号</div>
        <CheckboxGroup v-model="type">
          <Checkbox label="x0"></Checkbox>
          <Checkbox label="x1"></Checkbox>
          <Checkbox label="x2"></Checkbox>
        </CheckboxGroup>
      </div> -->
      <div slot="footer">
        <Button @click='typeModal=false'>关闭</Button>
        <Button type='primary' @click='saveNorms'>保存</Button>
      </div>
    </Modal>
  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import Tables from '_c/tables'
  //接口
  import {
    getNormsClass,
    addNorms,
    getNormsValueTemplateList
  } from '@/api/product-group/product-normstemplate'
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import {
    getTableData
  } from '@/api/data'
  export default {
    name: 'tables_page',
    components: {
      Tables
    },
    created() {

      this.getList()
    },
    watch: {

    },
    mounted() {

    },
    props: ['prodClassList'],
    computed: {
      ...mapState({
        productNormstemplateObj: state => state.share.productNormstemplateObj,
      }),
    },
    data() {
      return {
        secondForm: [{
          normsName: '',
          sub: [{
            name: ''
          }]
        }],
        normsForm: {},
        normsValidate: {},
        normsRuleValidate: {},
        normsName: [],
        prodModal: false,
        typeModal: false,
        type: '',
        searchObj: {
          name: ''
        },
        loadingText: '',
        formValidate: {},
        tableData: [],
        // 分页
        page: {
          pageSize: 10,
          current: 1,
          total: 0
        },
        // 分页end
        ruleValidate: {
          name: [{
            required: true,
            message: '请输入模板名称',
            trigger: 'blur'
          }],
        },
        tableOption: [{
            title: 'id',
            align: 'center',
            key: 'id'
          },
          {
            title: '租赁产品名称',
            align: 'center',
            key: 'name'
          },

          {
            title: '操作',
            slot: 'action',
            align: 'center'
          }

        ],
        data: {
          list: [{
            id: 1,
            name: '名称'
          }],
          normsTemplate: [{
              id: 34,
              name: '套餐',
              pid: 1,
              show: false,
              sub: [{
                id: 35,
                name: '7天',
                pid: 34,
                show: false
              }]
            },
            {
              id: 34,
              name: '套餐',
              pid: 1,
              show: false,
              sub: [{
                id: 35,
                name: '7天',
                pid: 34,
                show: false
              }]
            },
            {
              id: 34,
              name: '套餐',
              pid: 1,
              show: false,
              sub: [{
                id: 35,
                name: '7天',
                pid: 34,
                show: false
              }]
            }
          ]
        },
        editIndex: 0, // 当前聚焦的输入框的行数
        editName: '', // 第一列输入框，当然聚焦的输入框的输入内容，与 data 分离避免重构的闪烁
        editAge: '', // 第二列输入框
        editBirthday: '', // 第三列输入框
        editAddress: '', // 第四列输入框
      }
    },
    methods: {
      ...mapMutations([
        'setProductNormstemplateObj', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
        'setProductNormstemplateNorms'

      ]),
      addNormsItem(i) {

        let isAdd = true;
        this.normsName[i]['new_sub'].forEach(function(cv) {
          if (!cv.name) {
            isAdd = false;
          }

        })
        if (!isAdd) {
          let config = {
            content: '请先输入添加的项',
            background: true
          }
          this.$Message.error(config)
          return
        }
        let obj = {
          name: ''
        }
        //this.normsName[i]['new_sub']=[];
        this.normsName[i]['new_sub'].push(obj);

        //this.normsName[i].sub.push(obj);
      },

      addClass() {
        let _this = this;
        let isHasVal = true;
        this.secondForm.forEach(function(cv) {
          if (!cv.normsName) {
            isHasVal = false
          }
        })
        if (!isHasVal) {
          let config = {
            content: '请先填入规格名',
            background: true
          }
          _this.$Message.error(config);
          return

        }
        let obj = {
          normsName: '',
          sub: [{
            name: ''
          }]
        }
        this.secondForm.push(obj)
        console.log(this.secondForm)

      },
      addItem(i) {
        console.log(i)

        let obj = {
          name: ''
        }
        this.secondForm[i].sub.push(obj)
        // console.log(this.secondForm)

      },
      changeNewSub(i) {
        //this.normsName[i]['new_sub']=[];

        // this.normsName[i].sub.push(...this.normsName[i].new_sub)
        console.log(i)
      },
      // 列表数据
      getList() {
        let type = 'success'
        // this.$Message[type]({
        //   background: true,
        //   content: '这是一条带背景色的通知'
        // });
        //       [
        //         "285":{1,2,4},

        //       ]

      },
      search() {
        this.classList()
      },
      reset() {
        this.searchObj.name = '';
         this.classList()
      },
      classList() {
        let _this = this;
        this.prodModal = true;
        let params = {
          name: this.searchObj.name,
          page: this.page.current
        }

        getNormsClass(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data;
            _this.data.list = result.list;
            _this.page.total = result.total;
          } else {
            //axios响应拦截

          }

        }).catch(function(error) {
          //异常
         console.log(error)
        })
      },
      select(row) {
        this.prodModal = false;
        let obj = {
          template_norms_property_id: row.id,
          template_norms_property_name: row.name,
          name: this.productNormstemplateObj.name,
          is_norms: 0

        }
        this.setProductNormstemplateObj(obj)
        //template_norms_property_id
        console.log(this.productNormstemplateObj)
      },
      selectType() {
        if(!this.productNormstemplateObj.template_norms_property_id){
          this.$Message.error('请先选择顶级规格分类')
          return
        }
        let selectIds=[]
        if(this.productNormstemplateObj.norms && this.productNormstemplateObj.norms.length){
           selectIds=this.productNormstemplateObj.norms.map((res=>{return res.property_value_id}))//已选的
        }

        this.normsName=[];
        this.secondForm=[];
        let _this = this;
        this.typeModal = true;
        let params = {
          id: this.productNormstemplateObj.template_norms_property_id //对接口再赋值
        }
        getNormsValueTemplateList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data;
            _this.normsName = [];

            for (let key in result.normsTemplate) {
              result.normsTemplate[key]['itemGroup'] =selectIds;
              result.normsTemplate[key]['new_sub'] = [];
              _this.normsName.push(result.normsTemplate[key])
            }


          } else {
            //axios响应拦截

          }

        }).catch(function(error) {
          //异常
          console.log(error)
        })
      },
      saveNorms() {
       console.log(this.normsName);
       console.log(this.secondForm)
        let append_norms_property=this.normsName.map(function(cv,i){
          let obj={}
          obj[cv.id]=cv.new_sub.map((row=>{return row.name}))
          // let obj={
          //   cv[id]:cv.new_sub.map((row=>{return row.name}))

          // }
          return obj
        })
        // 2
        let norms_property=this.secondForm.map((res=>{
          return res.normsName
        }))
        let list=this.secondForm.map(function(cv,i){
          let obj=cv.sub.map(function(row,k){
            return row.name
          });

          return obj
        })
        let norms_property_item=[];
        list.forEach(function(cv,i){
          let obj={};
          cv.forEach(function(row,k){
            obj[k]=row
          })
          norms_property_item.push(obj)

        })


        //addNorms
        let _this=this;
        let params={
          norms_property_id:this.productNormstemplateObj.template_norms_property_id,//顶级分类id
          append_norms_property:{...append_norms_property},//[{"285":[1,2,3]}],
          norms_property:norms_property,
          norms_property_item:norms_property_item

        }
        addNorms(params).then(res => {
          if (res.data.status == 1) {

          } else {
            //axios响应拦截

          }

        }).catch(function(error) {
          //异常
          console.log(error)
        })




        let itemGroupTrueList = [];
        // 过滤被选中的
        itemGroupTrueList = this.normsName.filter((row => {
          return row.itemGroup.length
        }))
        let newList = [];

        itemGroupTrueList.forEach(function(cv) {
          let checkedSub = []
          let list = cv.itemGroup;
          // 返回选中的sub
          checkedSub = cv.sub.filter(function(row) {
            return list.indexOf(row.id) >= 0
          })
          let obj = {
            name: cv.name,
            id: cv.id,
            sub: checkedSub
          }
          newList.push(obj)


        })
        let norms = []
        console.log(newList)
        newList.forEach(function(item) {
          let list = item.sub.map(function(row) {
            return {

              property_name: item.name,
              property_id: item.id,
              property_value_name: row.name,
              property_value_id: row.id
            }
          })
          norms.push(...list)
        })
        console.log('opop')
        console.log(norms)

        this.setProductNormstemplateNorms(norms);
        this.typeModal = false;
      },
      changepage(e) {
        this.page.current = e;
        this.classList()();
      },
      handleEdit(row, index) {
        this.editName = row.name;
        this.editAge = row.age;
        this.editAddress = row.address;
        this.editBirthday = row.birthday;
        this.editIndex = index;
      },
      handleSave(index) {
        this.data[index].name = this.editName;
        this.data[index].age = this.editAge;
        this.data[index].birthday = this.editBirthday;
        this.data[index].address = this.editAddress;
        this.editIndex = -1;
      },
      getBirthday(birthday) {
        const date = new Date(parseInt(birthday));
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${year}-${month}-${day}`;
      },
      change(status) {
        this.$Message.info('开关状态：' + status);
      }
    },

  }
</script>

<style lang="scss">
  @import "./base-info";
</style>
